import {
  toast
} from '../../utils/util';
import wxApi from '../../utils/wxApi';
import {
  login
} from '../../api/login';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    barConTop: 0,
    barConHeight: 0,
    agreen: false,
    visible: false,
    agreements: [{
        title: '《服务协议》',
        content: '服务协议内容'
      },
      {
        title: '《隐私政策》',
        content: '隐私政策内容'
      },
    ],
    curAgreeMent: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.initBarCon();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  initBarCon() {

    // 状态栏信息-高度
    const status = wx.getSystemInfoSync();
    // 胶囊信息-高度及到顶高度
    const menu = wx.getMenuButtonBoundingClientRect();
    const barHeight = menu.height + (menu.top - status.statusBarHeight) * 2;
    this.setData({
      barConHeight: barHeight,
      barConTop: status.statusBarHeight
    });
  },
  async getPhoneNumber(e) {
    const {
      agreen
    } = this.data;
    if (!agreen) {
      toast('请认真阅读并勾选平台协议');
      return;
    }
    if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
      toast('您已取消授权');

      return;
    }
    const {
      code
    } = await wxApi('login');
    let phoneCode = e.detail.code
    let params = {
      phoneCode,
      loginCode: code,
      state: this.generateUUID()
    }
    const res = await login(params);
    wx.setStorageSync('Authorization', res.accessToken);
    wxApi('switchTab', {
      url: '/pages/home/home'
    });
  },
  generateUUID() {
    let timestamp = Date.now();
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (timestamp + Math.random() * 16) % 16 | 0;
      timestamp = Math.floor(timestamp / 16);
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });

    return uuid;
  },
  handlePopup(e) {
    this.setData({
      visible: true,
      curAgreeMent: e.currentTarget.dataset.item
    });
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  handleKnow() {
    this.setData({
      visible: false,
    });
  },
  agreeChange(e) {
    this.setData({
      agreen: e.detail.checked,
    });
  },
});